var express = require('express');
var router = express.Router();
var db = require('../core/mysql.js');
var util = require('util');
var mysql = require('mysql');
var cookie = require('cookie');
var parse = require('../public/javascripts/parse.js');

/* GET users listing. */
router.get('/toAdd', function(req, res, next) {
  res.render('publish/add' ,{title:'发表博客'});
});
router.get('/toDetail/:id/:link', function(req, res, next) {
  var id =req.params.id;
  var link = req.params.link;
  var sql = "select a.id,a.title,a.content,a.create_id createId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where a.id=:id";
  db.query(sql,{id:id},function(err,result){
      if(!err){ 
        if(result.length>0){
          result[0].link = link;
          res.render('publish/detail' ,result[0]);
        }
      }
  });
});
router.post('/add', function(req, res, next) {
	// 新增用户
  var title = req.body.title;
  if(!title){
     req.flash('error','标题不能为空');
     res.redirect('./add');
     return ;
  }
  req.cookies = parse.JSONCookies(cookie.parse(req.headers.cookie)); 
  var user = req.cookies.user;
  if(!user){
     req.flash('error','用户登录超时');
     res.redirect('/home');
     return ;
  }
  var sql = "insert into blog_publish(title,content,create_id) values (:title,:content,:createId)";
  db.query(sql,{title:title,content:req.body.content,createId:user.id},function(err,addRes){
  		if(!err){
        req.flash('success','发表成功');
        res.redirect('/home');
  		}
  });
});
router.get('/', function(req, res, next) {
  res.send('respond with a publish');
});

module.exports = router;
